package com.fh.controller.logAop;

/**
 * Created by caozengling on 2018/7/21.
 */


import com.fh.dao.DaoSupport;
import com.fh.entity.system.User;
import com.fh.service.building.RecordService;
import com.fh.util.*;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * 日志切面实现
 */

@Component
@Aspect
public class LogService {

    @Resource(name = "daoSupport")
    private DaoSupport dao;
    @Resource(name = "recordService")
    private RecordService recordService;

    public LogService() {
        System.out.println("Aop");
    }

    /**
     * 切点
     */
    @Pointcut("@annotation(com.fh.controller.logAop.MethodLog)")
    public void methodCachePointcut() { }


    /**
     * 切面
     *
     * @param point
     * @return
     * @throws Throwable
     */
    @Around("methodCachePointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {

        String methodRemark = getMthodRemark(point);
        String methodName = point.getSignature().getName();
        String operatingcontent = "";
        Object[] method_param = null;
        Object object;
        try {
            method_param = point.getArgs(); //获取方法参数
//            HttpServletRequest req = (HttpServletRequest) method_param[0];
            // String param=(String) point.proceed(point.getArgs());
            object = point.proceed();
            JSONObject array=JSONHelper.toJSONObject(object);
            Map<String, Object> resData=JSONHelper.json2Map(array.get("data").toString());//pd 中的所有参数值
            //获取当前登录用户
            Subject currentUser = SecurityUtils.getSubject();
            Session session = currentUser.getSession();
            User user = (User) session.getAttribute(Const.SESSION_USER);
            //保存操作记录
            PageData oppd = new PageData();
            oppd.put("ID",UuidUtil.get32UUID());    //主键
            oppd.put("IS_DEL", 0); //是否删除
            oppd.put("SORT", 0); //排序
            oppd.put("CREATE_ID", user.getUSER_ID()); //创建用户
            oppd.put("CREATE_DATE", new DateUtil().getTime()); //创建时间
            oppd.put("OPERA_TIME", new DateUtil().getTime());
            oppd.put("OPERATOR", user.getNAME());
            oppd.put("DETAILS", resData.get("DETAILS"));
            recordService.save(oppd);
        } catch (Exception e) {
            // 异常处理记录日志..log.error(e);
            throw e;
        }

//        if("新增用户".equals(methodRemark)){
//            HttpServletRequest req = (HttpServletRequest) method_param[0];
//            sysLog.setOperatingcontent("新增用户: 用户名为 " + req.getParameter("userName"));
//
//        }
//        System.out.println("日志实体："+sysLog.getLoginName()+sysLog.getMethodRemark()+sysLog.getOperatingcontent());
        return object;

    }

    /**
     * 方法异常时调用
     *
     * @param ex
     */
    public void afterThrowing(Exception ex) {
        System.out.println("afterThrowing");
        System.out.println(ex);
    }

    /**
     * 获取方法中的中文备注
     *
     * @param joinPoint
     * @return
     * @throws Exception
     */
    public static String getMthodRemark(ProceedingJoinPoint joinPoint) throws Exception {

        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();

        Class targetClass = Class.forName(targetName);
        Method[] method = targetClass.getMethods();
        String methode = "";
        for (Method m : method) {
            if (m.getName().equals(methodName)) {
                Class[] tmpCs = m.getParameterTypes();
                if (tmpCs.length == arguments.length) {
                    MethodLog methodCache = m.getAnnotation(MethodLog.class);
                    if (methodCache != null) {
                        methode = methodCache.remark();
                    }
                    break;
                }
            }
        }
        return methode;
    }
}
